<?php
namespace backend\controllers;

use Yii;

use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;

use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use backend\base\BaseBackendController;
use base\YiiMobo;
use backend\models\Post;
use yii\web\UploadedFile; 


use common\components\Uploader;
/*
* 百度编辑器 & 上传图片
*/
class UeditorController extends BaseBackendController
{


	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout= false;
	
	public $enableCsrfValidation = false;
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['index','upload'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionIndex()
	{
		$configfiles = "../static/ueditor/config.json";
		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($configfiles)), true);
		$action = $_GET['action'];
		
		switch ($action) {
			case 'config':
				$result =  json_encode($CONFIG);
				break;
		
			/* 上传图片 */
			case 'uploadimage':
			/* 上传涂鸦 */
			case 'uploadscrawl':
			/* 上传视频 */
			case 'uploadvideo':
			/* 上传文件 */
			case 'uploadfile':
				$result = $this->actionUpload();
				break;
		
			/* 列出图片 */
			case 'listimage':
				//$result = include("action_list.php");
				break;
			/* 列出文件 */
			case 'listfile':
				//$result = include("action_list.php");
				break;
		
			/* 抓取远程文件 */
			case 'catchimage':
				//$result = include("action_crawler.php");
				break;
		
			default:
				$result = json_encode(array(
					'state'=> '请求地址出错'
				));
				break;
		}
		
		/* 输出结果 */
		if (isset($_GET["callback"])) {
			if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
				echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
			} else {
				echo json_encode(array(
					'state'=> 'callback参数不合法'
				));
			}
		} else {
			echo $result;
		}
	}


	/**
	 * 通用上传接口 包括百度编辑器上传接口
	 * @param NULL
	 * @author xiong
	 */
	public function actionUpload(){
		//error_reporting( E_ERROR | E_WARNING );
		$rootpath = dirname(Yii::getAlias('@web')).'/';
		$config = array(
		    "savePath" => "../uploads/picture",
			"maxSize" => isset($_POST['maxSize']) ? intval($_POST['maxSize']) : 20000,                   //允许的文件最大尺寸，单位KB
			"allowFiles" => isset($_POST['fileTypeExts']) ? explode(';', str_replace('*','', trim($_POST['fileTypeExts']))) : array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp" ),  //允许的文件格式
			"thumbWidth" => isset($_POST['thumbWidth']) ? $_POST['thumbWidth'] : 600,
		);
        //$config["savePath"] .= isset($_POST['savePath']) ? $_POST['savePath'] : '';
		$up = new Uploader( "upfile" , $config );

		$callback = isset($_GET['callback']) ? $_GET['callback'] : '';
		$module = isset($_POST['module']) ? $_POST['module'] : 'post';
		$info = $up->getFileInfo();
		/**
		 * 返回数据
		 */
		if($callback) {
			echo '<script>'.$callback.'('.json_encode($info).')</script>';
		} else {
			if ($info['state'] == "SUCCESS") {
				$info['url'] = str_replace('../', '', $info['url']);
				if (isset($_GET['fullpath']) && $_GET['fullpath'] == 'true') $info['url'] = Yii::$app->request->hostInfo.$this->root_dir.'/'.$info['url'];
			}else{
				$info['error'] = '';
			}
			
			echo json_encode($info);
		}
		exit();
	}
    public function actionUploadss(){
	
	   //$upload = $this->uploadedFile(new Post(), 'upfile');
	   $uploadpath = 'uploads/';
       $image = UploadedFile::getInstance(new Post(), 'upfile');
            $ext = $image->getExtension();
            $randName = time() . rand(1000, 9999) . "." . $ext;
            $path = abs(crc32($randName) % 500);
            $rootPath = $rootPath . $path . "/";
            if (!file_exists($path)) {
                mkdir($rootPath,true);
            }
            $image->saveAs($rootPath . $randName);
		
	
    }
    public function uploadedFile($model, $item)
    {
        $upload = UploadedFile::getInstance($model, $item);
        

        return $upload;
    }

    public function fileExists($uploadpath)
    {

        if(!file_exists($uploadpath)){
            mkdir($uploadpath, true);
        }

        return $uploadpath;
    }

}
